package com.psak.cudaphrasal.client.task;

import java.io.Serializable;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.apache.log4j.Logger;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

import com.psak.cudaphrasal.client.task.processing.TaskProcessingException;
import com.psak.cudaphrasal.client.task.processing.TaskProcessingService;
import com.psak.cudaphrasal.model.FileChunkToProcess;
import com.psak.cudaphrasal.model.ProcessingResult;

public class TaskMessageListener implements MessageListener {

	private static Logger LOG = Logger.getLogger(TaskMessageListener.class);

	private TaskProcessingService taskProcessingService;
	private JmsTemplate jmsTemplate;
	private String queueName;
	private String processPath;

	@Override
	public void onMessage(Message message) {
		if (message instanceof ObjectMessage) {
			ObjectMessage objectMessage = (ObjectMessage) message;
			try {
				Serializable messageContent = objectMessage.getObject();
				if (messageContent instanceof FileChunkToProcess) {
					FileChunkToProcess chunk = (FileChunkToProcess) messageContent;
					final ProcessingResult processingResult = taskProcessingService
							.processChunk(chunk, processPath);
					jmsTemplate.send(queueName, new MessageCreator() {

						@Override
						public Message createMessage(Session session)
								throws JMSException {
							ObjectMessage messageToSend = session
									.createObjectMessage();
							messageToSend.setObject(processingResult);
							return messageToSend;
						}
					});
				}
			} catch (JMSException e) {
				LOG.error("Blad kolejki", e);
			} catch (TaskProcessingException e) {
				LOG.error("Blad przetwarzania paczki", e);
			}
		}
	}

	public void setTaskProcessingService(
			TaskProcessingService taskProcessingService) {
		this.taskProcessingService = taskProcessingService;
	}

	public void setQueueName(String queueName) {
		this.queueName = queueName;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

	public void setProcessPath(String processPath) {
		this.processPath = processPath;
	}

}
